﻿/*
*VMukti -- An open source video conferencing platform.
*
* Copyright (C) 2007 - 2008, VMukti Solutions Pvt. Ltd.
*
* Hardik Sanghvi <hardik@vmukti.com>
*
* See http://www.vmukti.com for more information about
* the VMukti project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, forums and mailing lists
* for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using System.Net;
using System.Reflection;
using VMukti.Business.WCFServices.BootStrapServices.BasicHttp;
using VMuktiService;
using VMukti.Business.WCFServices.SuperNodeServices.BasicHttp;
using VMukti.Business.WCFServices.BootStrapServices.NetP2P;
using VMukti.Business.WCFServices.SuperNodeServices.NetP2P;
using System.Security.Permissions;
using VMuktiAPI;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Data.SqlServerCe;
using System.Data.SqlServerCe;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.Server;
//using VMukti.Bussiness.WCFServices.BootStrapServices.NetP2P;
//using VMukti.Business.WCFServices.BootStrapServices.NetP2P;
using VMukti.ZipUnzip.Zip;
using VMukti.Presentation.Domains;
using System.Threading;
using System.IO;
using System.Windows.Interop;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Text;
using LumiSoft.Net.STUN.Client;
using VMukti.Business.WCFServices.BootStrapServices.DataContracts;
using VMukti.Business.WCFServices.SuperNodeServices.DataContract;

namespace VMukti
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	/// 
	public partial class App : Application, IDisposable
	{
		#region Http Clients

		public static IHTTPBootStrapService chHttpBootStrapService = null;
		public static BasicHttpClient objHttpBootStrap = new BasicHttpClient();

		//public static IHttpSuperNodeService chHttpAuthSuperNodeService = null;
		//public static BasicHttpClient objHttpAuthSuperNode = new BasicHttpClient();

		public static IHttpSuperNodeService chHttpSuperNodeService = null;
		public static BasicHttpClient objHttpSuperNode = new BasicHttpClient();

        //public static IHttpDataBaseService chHttpDataBaseService = null;
        //public static BasicHttpClient objHttpDataBase = new BasicHttpClient();

		#endregion

		#region NetP2P Clients

		public static object objNetP2PSuperNode = null;
		public static INetP2PSuperNodeChannel chNetP2PSuperNodeChannel = null;

        public static int pageCounter = 0;
        public static int tabCounter = 0;
        public static int podCounter = 0;

		//public static object objNetP2PBootStrapActiveCallReport = null;
		//public static INetP2PBootStrapReportChannel chNetP2PBootStrapActiveCallReportChannel = null;

		//public static object objNetP2PBootStrapActiveAgentReport = null;
		//public static INetP2PBootStrapActiveAgentReportChannel chNetP2PBootStrapActiveAgentReportChannel = null;


		#endregion

		//object objBootStrap = null;
		//object objSuperNode = null;

		//public static string strCurrentBSIP = string.Empty;
		//public static string strCurrentMachineIP = string.Empty;

		System.Xml.XmlNodeList xmlNodes = null;
		AppDomainSetup DomainSetUp = null;

		Thread thBootStrapDomain = null;
		Thread thSuperNodeDomain = null;
		string strFilePath = string.Empty;
        StringBuilder sb1 = new StringBuilder();
		private bool disposed = false;




		protected override void OnStartup(StartupEventArgs e)
		{
			try
			{
				Application.SetCookie(BrowserInteropHelper.Source, "Login");
				try
				{
					try
					{
						StreamWriter sWriter = null;
						strFilePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\DomainStatus.txt";
						if (!File.Exists(strFilePath))
						{
							sWriter = new StreamWriter(File.Create(strFilePath));
						}
						else
						{
							sWriter = new StreamWriter(strFilePath);
						}
						sWriter.Write("Initializing");
						sWriter.Close();
					}
					catch (Exception ex)
					{
						ex.Data.Add("My Key", "Error in DomainSTatus.txt file operation()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
						ClsException.LogError(ex);
						ClsException.WriteToErrorLogFile(ex);
					}

                    //List<string> tempLst = new List<string>();
                    //tempLst = VMuktiAPI.VMuktiInfo.BootStrapIPs;
                    //tempLst.Add(System.Deployment.Application.ApplicationDeployment.CurrentDeployment.ActivationUri.AbsoluteUri.ToString().Replace("http://", "").Substring(0, System.Deployment.Application.ApplicationDeployment.CurrentDeployment.ActivationUri.AbsoluteUri.ToString().Replace("http://", "").IndexOf('/')));
                    //VMuktiAPI.VMuktiInfo.BootStrapIPs = tempLst;

                    string str = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.ActivationUri.AbsoluteUri.ToString();
                    string strTemp = str;
                    str = str.ToLower();
                    int i = str.IndexOf("vmukti.presentation.xbap".ToLower());
                    VMuktiAPI.VMuktiInfo.ZipFileDownloadLink = strTemp.Substring(0, i);
                    new WebClient().DownloadFile(VMuktiAPI.VMuktiInfo.ZipFileDownloadLink + "Configuration.xml", AppDomain.CurrentDomain.BaseDirectory.ToString() + "Configuration.xml");

                    System.Xml.XmlDocument ConfDoc = new System.Xml.XmlDocument();
                    ConfDoc.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + "Configuration.xml");
                    System.Xml.XmlNodeList xmlNodes = null;
                    xmlNodes = ConfDoc.GetElementsByTagName("BootStrpIP");

                    List<string> tempLst = new List<string>();
                    tempLst = VMuktiAPI.VMuktiInfo.BootStrapIPs;
                    tempLst.Add(xmlNodes[0].Attributes["Value"].Value.ToString());
                    VMuktiAPI.VMuktiInfo.BootStrapIPs = tempLst;

					//if (!System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory.ToString() + "Orka.zip"))
					//{
					//    new WebClient().DownloadFile("http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + "/VMukti/Orka.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "Orka.zip");
					//    FastZip fz = new FastZip();
					//    fz.ExtractZip(AppDomain.CurrentDomain.BaseDirectory.ToString() + "Orka.zip", AppDomain.CurrentDomain.BaseDirectory.ToString() + "Orka", null);
					//}

				}
				catch
				{
					List<string> tempLst = new List<string>();
					//tempLst = VMuktiAPI.VMuktiInfo.BootStrapIPs;
                    tempLst.Add("192.168.191.182");

					// COmment below two lines for vista related changes and put new two lines instad of that
					//VMuktiAPI.VMuktiInfo.BootStrapIPs.Add(System.Net.Dns.GetHostEntry(System.Environment.MachineName).AddressList[0].ToString());
					//VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP = System.Net.Dns.GetHostEntry(System.Environment.MachineName).AddressList[0].ToString();
					VMuktiAPI.VMuktiInfo.BootStrapIPs.Add("192.168.191.182");
                    VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP = "192.168.191.182";
					// End Vista related changes.

					VMuktiAPI.VMuktiInfo.BootStrapIPs = tempLst;
                    VMuktiAPI.VMuktiInfo.ZipFileDownloadLink = "http://192.168.191.190/Vmukti/";
					VMuktiAPI.VMuktiInfo.MainConnectionString = @"~Data Source=192.168.191.190\SQLExpress;Initial Catalog=VMukti;User ID=sa;PassWord=mahavir";
				}

				for (int i = 0; i < System.Net.Dns.GetHostEntry(System.Environment.MachineName).AddressList.Length; i++)
				{
					int j = 0;

					List<string> tempLst = new List<string>();
					tempLst = VMuktiAPI.VMuktiInfo.CurrentPeer.NodeIPs;

					tempLst.Add(System.Net.Dns.GetHostEntry(System.Environment.MachineName).AddressList[i].ToString());

					VMuktiAPI.VMuktiInfo.CurrentPeer.NodeIPs = tempLst;

					for (j = 0; j < VMuktiAPI.VMuktiInfo.BootStrapIPs.Count; j++)
					{
						if (VMuktiAPI.VMuktiInfo.CurrentPeer.NodeIPs[i] == VMuktiAPI.VMuktiInfo.BootStrapIPs[j])
						{
							break;
						}
					}
					if (j < VMuktiAPI.VMuktiInfo.BootStrapIPs.Count)
					{
						VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.BootStrap;

						VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP = VMuktiAPI.VMuktiInfo.BootStrapIPs[j];

						VMuktiAPI.VMuktiInfo.CurrentPeer.Port1433Status = VMuktiAPI.PortStatus.InOutBoundOpen;
						VMuktiAPI.VMuktiInfo.CurrentPeer.Port4000Status = VMuktiAPI.PortStatus.InOutBoundOpen;
						VMuktiAPI.VMuktiInfo.CurrentPeer.Port5060Status = VMuktiAPI.PortStatus.InOutBoundOpen;
					}
				}
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "OnStartup()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
			}

			#region Functions which will make decision whether node/supernode

			if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.BootStrap)
			{
				DomainSetUp = new AppDomainSetup();
				DomainSetUp.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
				DomainSetUp.ConfigurationFile = AppDomain.CurrentDomain.BaseDirectory + "VMukti.Presentation.exe.config";

				if (!System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory.ToString() + "Configuration.xml"))
				{
                    new WebClient().DownloadFile(VMuktiAPI.VMuktiInfo.ZipFileDownloadLink + "Configuration.xml", AppDomain.CurrentDomain.BaseDirectory.ToString() + "Configuration.xml");
				}
				System.Xml.XmlDocument ConfDoc = new System.Xml.XmlDocument();
				ConfDoc.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + "Configuration.xml");
				xmlNodes = ConfDoc.GetElementsByTagName("AuthServer");

				VMuktiAPI.VMuktiInfo.CurrentPeer.AuthServerIP = xmlNodes[0].Attributes["IPAddresss"].Value.ToString();

				if (xmlNodes[0].Attributes["AuthType"].Value.ToString() == "SQL")
				{
					VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType = VMuktiAPI.AuthType.SQLAuthentication;
					xmlNodes = ConfDoc.GetElementsByTagName("SQLInfo");
					if (VMuktiAPI.VMuktiInfo.MainConnectionString.StartsWith("~"))
					{
						VMuktiAPI.VMuktiInfo.MainConnectionString = VMuktiAPI.VMuktiInfo.MainConnectionString.Substring(1);
					}
					else
					{
						VMuktiAPI.VMuktiInfo.MainConnectionString = "Data Source=" + xmlNodes[0].Attributes["SQLInstanceName"].Value.ToString() + ";Initial Catalog=" + xmlNodes[0].Attributes["DatabaseName"].Value.ToString() + ";User ID=" + xmlNodes[0].Attributes["SQLUserName"].Value.ToString() + ";PassWord=" + xmlNodes[0].Attributes["SQLPassword"].Value.ToString();
					}
				}
				else if (xmlNodes[0].Attributes["AuthType"].Value.ToString() == "SIP")
				{
					VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType = VMuktiAPI.AuthType.SIPAuthentication;
				}


				thBootStrapDomain = new Thread(new ThreadStart(LoadBootStrap));
				thBootStrapDomain.Priority = ThreadPriority.Highest;
				thBootStrapDomain.Start();
			}

			if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.NotDecided)
			{
				try
				{
					if (FncInLan(VMuktiAPI.VMuktiInfo.BootStrapIPs[0]))
					{
						//System In LAN

						#region Deciding peerType for Vista System
						if (FncVistaOS())
						{
							if (FncVistaLocalFireWall())
							{
								VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
							}
							else
							{
								if (FncPort4000Free())
								{
									if (FncPort80Free())
									{
										VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.SuperNode;
										VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP = GetIP4Address();

										DomainSetUp = new AppDomainSetup();
										DomainSetUp.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
										DomainSetUp.ConfigurationFile = AppDomain.CurrentDomain.BaseDirectory + "VMukti.Presentation.exe.config";

										thSuperNodeDomain = new Thread(new ThreadStart(LoadSuperNode));
										thSuperNodeDomain.Priority = ThreadPriority.Normal;
										thSuperNodeDomain.Start();
									}
									else
									{
										VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
										//VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithNetP2P;
									}
								}
								else
								{
									VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
								}
							}
						}
						#endregion

						#region Deciding PeerType for NonVista Systems
						else
						{
							if (FncLocalFirewall())
							{
								VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
							}
							else
							{
								if (FncPort4000Free())
								{
									if (FncPort80Free())
									{
										//systen is SUPERNODE
										VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.SuperNode;
										VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP = GetIP4Address();

										DomainSetUp = new AppDomainSetup();
										DomainSetUp.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
										DomainSetUp.ConfigurationFile = AppDomain.CurrentDomain.BaseDirectory + "VMukti.Presentation.exe.config";

										thSuperNodeDomain = new Thread(new ThreadStart(LoadSuperNode));
										thSuperNodeDomain.Priority = ThreadPriority.Normal;
										thSuperNodeDomain.Start();

									}
									else
									{
										VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
										//VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithNetP2P;
									}
								}
								else
								{
									VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
								}
							}
						}
						#endregion

					}
					else
					{
						#region Definding PeerType for LiveIP system
						if (FncIsLiveIP())
						{
							if (FncFireWall())
							{
								VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
								ClsException.WriteToLogFile("In LIve IP :: Fire Wall is true in LiveIP  in FncFireWall means node with http");
							}
							else
							{
								if (FncPort4000Free())
								{
									if (FncPort80Free())
									{
										//System is SUPERNODE

										VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.SuperNode;
										VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP = GetIP4Address();
										DomainSetUp = new AppDomainSetup();
										DomainSetUp.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
										DomainSetUp.ConfigurationFile = AppDomain.CurrentDomain.BaseDirectory + "VMukti.Presentation.exe.config";

										thSuperNodeDomain = new Thread(new ThreadStart(LoadSuperNode));
										thSuperNodeDomain.Priority = ThreadPriority.Highest;
										thSuperNodeDomain.Start();
										ClsException.WriteToLogFile("In Live IP :: FncPort80Free is true means supernode");
									}
									else
									{
										//PeerType nodewithhttp
										VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
										//VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithNetP2P;
										ClsException.WriteToLogFile("In Live IP :: FncPort80Free is false that means node with NodeWithHttp");
									}
								}
								else
								{
									VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
									ClsException.WriteToLogFile("In Live IP :: FncPort4000Free is false that means node with http");
								}
							}
						}
						#endregion

						#region Deciding PeerType for NonLiveIP System
						else
						{
							if (FncFireWall())
							{
								VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
								ClsException.WriteToLogFile("In not live IP function FncFireWall is ture that means node with http");
							}
							else
							{
								if (FncPort4000Free())
								{
									//VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithNetP2P;
									VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
									ClsException.WriteToLogFile("In not live IP function FncPort4000Free is ture that means node with NodeWithHttp");
								}
								else
								{
									VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType = VMuktiAPI.PeerType.NodeWithHttp;
									ClsException.WriteToLogFile("In not live IP function FncPort4000Free is ture that means node with http");
								}
							}
						}
						#endregion
					}
					ClsException.WriteToLogFile("System Type:" + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
				}
				catch (Exception ex)
				{
					//MessageBox.Show(ex.Message);
					ex.Data.Add("My Key", "OnStartup()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
					ClsException.LogError(ex);
					ClsException.WriteToErrorLogFile(ex);
				}
			}

			#endregion

            //System.IO.FileInfo fi = new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory.ToString() + "Configuration.xml");
            //if (fi.Exists)
            //{
            //    fi.Delete();
            //}

			if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType != PeerType.BootStrap)
			{
                OpenBootStrapHttpClient();
            }

            //11-Feb-2008
            //shilpa code
            VMuktiAPI.VMuktiHelper.RegisterEvent("GetSuperNodeIP").VMuktiEvent += new VMuktiEvents.VMuktiEventHandler(App_VMuktiEvent_GetSuperNodeIP);

			Application.Current.MainWindow.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
			base.OnStartup(e);
            DownLoadVideoExe();
		}

        void DownLoadVideoExe()
        {
            //string filename = "VideoExe.zip";
            //Uri u = new Uri(VMuktiAPI.VMuktiInfo.ZipFileDownloadLink + filename);
            //string destination = AppDomain.CurrentDomain.BaseDirectory.ToString() + "";
            //if (!File.Exists(destination + "\\" + filename))
            //{
            //    WebClient wc = new WebClient();
            //    wc.DownloadFile(u, destination + "\\" + filename);
            //}

            //VMukti.ZipUnzip.Zip.FastZip fz = new FastZip();
            //if (!Directory.Exists(destination + "\\" + filename)) 
            //{
            //    fz.ExtractZip(destination + "\\" + filename, destination, null);
            //}
           
        }

        //11-Feb-2008
        //shilpa code
        void App_VMuktiEvent_GetSuperNodeIP(object sender, VMuktiEventArgs e)
        {
            //Assign new supenode and start new channels 
            //for database and for other services
            try
            {
                //store previous supernode to offline its buddy
                string PreviousSuperNode = VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP;
                
                // ** SuperNode is down ::  PreviousSuperNode

                StringBuilder sb = new StringBuilder();
                sb1 = CreateTressInfo();
                sb.AppendLine("Initializing: SuperNode Is Down" + PreviousSuperNode);
                sb.AppendLine(sb1.ToString());
                ClsLogging.WriteToTresslog(sb);
               

                string SuperNodeName = null;
                if (PreviousSuperNode != null || PreviousSuperNode != string.Empty)
                {
                    
                    SuperNodeName = App.chHttpBootStrapService.svcGetNodeNameByIP(PreviousSuperNode);
                }              
                clsSuperNodeDataContract objSuperNodeDataContract;

                try
                {
                    // ** Taking new supernode from bootstap
                    StringBuilder sb2 = new StringBuilder();
                    sb1 = CreateTressInfo();
                    sb2.AppendLine("Initializing: Taking New supernode from Bootstrap");
                    sb2.AppendLine(sb1.ToString());
                    ClsLogging.WriteToTresslog(sb2);
               
                    objSuperNodeDataContract = App.chHttpBootStrapService.svcHttpBsGetSuperNodeIP(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, GetIP4Address(), false);

                    //open database channel
                    StringBuilder sb3 = new StringBuilder();
                    sb1 = CreateTressInfo();
                    sb3.AppendLine("Initializing: Opening Database Channel");
                    sb3.AppendLine(sb1.ToString());
                    ClsLogging.WriteToTresslog(sb3);
               
                    VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP = objSuperNodeDataContract.SuperNodeIP;
                    
                    // ** New assigned supernode is :: VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP 
                    StringBuilder sb4 = new StringBuilder();
                    sb1 = CreateTressInfo();
                    sb4.AppendLine("Initializing:  New assigned supernode is " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                    sb4.AppendLine(sb1.ToString());
                    ClsLogging.WriteToTresslog(sb4);
                    Business.clsDataBaseChannel.OpenDataBaseClient();

                    //open other service channel
                    // ** Opening New sueprnode client VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP
                    StringBuilder sb5 = new StringBuilder();
                    sb1 = CreateTressInfo();
                    sb5.AppendLine("Initializing: open other service channel " );
                    sb5.AppendLine("Opening New Supernode client " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                    sb5.AppendLine(sb1.ToString());
                    ClsLogging.WriteToTresslog(sb5);

                    App.chHttpSuperNodeService = (IHttpSuperNodeService)App.objHttpSuperNode.OpenClient<IHttpSuperNodeService>("http://" + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP + ":80/HttpSuperNode");
                    App.chHttpSuperNodeService.svcJoin(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());

                    if (SuperNodeName != null || SuperNodeName != string.Empty)
                    {
                        App.chHttpSuperNodeService.svcGetNodeNameByIP(SuperNodeName, PreviousSuperNode);                       
                    }

                }
                catch (System.ServiceModel.EndpointNotFoundException ex)
                {
                    //stop all other timer
                    VMuktiAPI.VMuktiHelper.CallEvent("StopTimer", null, null);
                    //and start one timer for the checking upto boostrap found
                    MessageBox.Show("Can not connect to Server , Please try after some Time.");
                }
                catch (System.ServiceModel.CommunicationException ex)
                {
                    //stop all other timer
                    VMuktiAPI.VMuktiHelper.CallEvent("StopTimer", null, null);
                    //and start one timer for the checking upto boostrap found
                    MessageBox.Show("Can not connect to Server , Please try after some Time.");
                }



            }
            catch (Exception ex)
            {

                ex.Data.Add("My Key", "App_VMuktiEvent_GetSuperNodeIP()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }
        //11-Feb-2008
        //end shilpa code

		private void WriteDomainStatus(string strStatus)
		{
			try
			{
				StreamWriter sWriter = new StreamWriter(strFilePath);
				sWriter.Write(strStatus);
				sWriter.Close();
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "WriteDomainStatus()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
			}
		}

		private void LoadBootStrap()
		{
			try
			{
				//VMuktiAPI.VMuktiInfo.BootStrapDomain = AppDomain.CreateDomain("BootStrapDomain", new System.Security.Policy.Evidence(), DomainSetUp, new System.Security.PermissionSet(PermissionState.Unrestricted));
				VMuktiAPI.VMuktiInfo.BootStrapDomain = AppDomain.CreateDomain("BootStrapDomain", null, DomainSetUp, new System.Security.PermissionSet(PermissionState.Unrestricted));
				VMuktiAPI.VMuktiInfo.BootStrapDomain.ApplicationTrust.ExtraInfo = AppDomain.CurrentDomain.ApplicationTrust.ExtraInfo;
				VMuktiAPI.VMuktiInfo.BootStrapDomain.ApplicationTrust.DefaultGrantSet = new System.Security.Policy.PolicyStatement(new System.Security.PermissionSet(PermissionState.Unrestricted));
				VMuktiAPI.VMuktiInfo.BootStrapDomain.ApplicationTrust.IsApplicationTrustedToRun = true;
				VMuktiAPI.VMuktiInfo.BootStrapDomain.ApplicationTrust.Persist = true;
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "OnStartup()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
			}
			//   MessageBox.Show("10");
			try
			{
				WriteDomainStatus("BootStrapDomain");
				VMuktiAPI.VMuktiInfo.BootStrapDomain.CreateInstance("VMukti.Presentation", "VMukti.Presentation.BootstrapServiceDomain");

				//chHttpBootStrapService = (IHTTPBootStrapService)objHttpBootStrap.OpenClient<IHTTPBootStrapChannel>("http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + ":80/HttpBootStrap");
                OpenBootStrapHttpClient();

                //if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == PeerType.BootStrap)
                //{
					try
					{
						System.Threading.Thread tupload = new System.Threading.Thread(new System.Threading.ThreadStart(StartUpload));
						tupload.Start();
					}
					catch (Exception ex)
					{
						ex.Data.Add("My Key", "PresentationUploadThread--:--App.xaml.cs--:--" + ex.Message + " :--:--");
						ClsException.LogError(ex);
						ClsException.WriteToErrorLogFile(ex);
					}
                //}
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "OnStartup()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
			}
			thSuperNodeDomain = new Thread(new ThreadStart(LoadSuperNode));
			thSuperNodeDomain.Priority = ThreadPriority.Highest;
			thSuperNodeDomain.Start();
		}

		private void LoadSuperNode()
		{
			try
			{
				//VMuktiAPI.VMuktiInfo.SuperNodeDomain = AppDomain.CreateDomain("SuperNodeDomain", null, DomainSetUp);
				//VMuktiAPI.VMuktiInfo.SuperNodeDomain = AppDomain.CreateDomain("SuperNodeDomain", new System.Security.Policy.Evidence(), DomainSetUp, new System.Security.PermissionSet(PermissionState.Unrestricted));

				VMuktiAPI.VMuktiInfo.SuperNodeDomain = AppDomain.CreateDomain("SuperNodeDomain", null, DomainSetUp, new System.Security.PermissionSet(PermissionState.Unrestricted));
				VMuktiAPI.VMuktiInfo.SuperNodeDomain.ApplicationTrust.ExtraInfo = AppDomain.CurrentDomain.ApplicationTrust.ExtraInfo;
				VMuktiAPI.VMuktiInfo.SuperNodeDomain.ApplicationTrust.DefaultGrantSet = new System.Security.Policy.PolicyStatement(new System.Security.PermissionSet(PermissionState.Unrestricted));
				VMuktiAPI.VMuktiInfo.SuperNodeDomain.ApplicationTrust.IsApplicationTrustedToRun = true;
				VMuktiAPI.VMuktiInfo.SuperNodeDomain.ApplicationTrust.Persist = true;

				WriteDomainStatus("SuperNodeDomain");
				VMuktiAPI.VMuktiInfo.SuperNodeDomain.CreateInstance("VMukti.Presentation", "VMukti.Presentation.SuperNodeServiceDomain");
				WriteDomainStatus("Initializing");
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "GetIP4Address--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
			}
		}

        private void OpenBootStrapHttpClient()
        {
            try
            {
                // ** Opening Bootstrap client
                // VMuktiAPI.VMuktiInfo.BootStrapIPs[0] 
                StringBuilder sb = new StringBuilder();
                sb1 = CreateTressInfo();
                sb.AppendLine("Initializing: Opening Bootstrap client ");
                sb.AppendLine("Client Is " + VMuktiAPI.VMuktiInfo.BootStrapIPs[0]);
                sb.AppendLine(sb1.ToString());
                ClsLogging.WriteToTresslog(sb);
                chHttpBootStrapService = (IHTTPBootStrapService)objHttpBootStrap.OpenClient<IHTTPBootStrapChannel>("http://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + ":80/HttpBootStrap");
                clsBootStrapInfo objBootStrapInfo = null;
                objBootStrapInfo = App.chHttpBootStrapService.svcHttpBSJoin("", null);

                // ** Client Open Sucessfully
                StringBuilder sb3 = new StringBuilder();
                sb1 = CreateTressInfo();
                sb3.AppendLine("Initializing: Client Open Sucessfully ");
                sb3.AppendLine("Client Is: " + VMuktiAPI.VMuktiInfo.BootStrapIPs[0]);
                sb3.AppendLine("Main Connection string is : " + VMuktiAPI.VMuktiInfo.MainConnectionString);
                sb3.AppendLine("Authentation type is : " + objBootStrapInfo.AuthType);
                sb3.AppendLine(sb1.ToString());
                ClsLogging.WriteToTresslog(sb3);
                // VMuktiAPI.VMuktiInfo.BootStrapIPs[0] 
                // Main Connection string is : VMuktiAPI.VMuktiInfo.MainConnectionString
                // Authentation type is : objBootStrapInfo.AuthType

                VMuktiAPI.VMuktiInfo.MainConnectionString = objBootStrapInfo.ConnectionString;

                switch (objBootStrapInfo.AuthType)
                {
                    case "SIPAuthentication":
                        VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType = AuthType.SIPAuthentication;
                        break;

                    case "SQLAuthentication":
                        VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType = AuthType.SQLAuthentication;
                        break;

                    default:
                        VMuktiAPI.VMuktiInfo.CurrentPeer.CurrAuthType = AuthType.NotDecided;
                        break;

                }
                bool isSuperNode = false;
                if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.NodeWithHttp || VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.NodeWithNetP2P)
                {
                    isSuperNode = false;
                }
                else if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.BootStrap || VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.SuperNode)
                {
                    isSuperNode = true;
                }
                if(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName == string.Empty)
                {
					VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName = GetIP4Address();
                }

                        
				
                clsSuperNodeDataContract objSuperNodeDataContract = App.chHttpBootStrapService.svcHttpBsGetSuperNodeIP(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, GetIP4Address(), isSuperNode);
                VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP = objSuperNodeDataContract.SuperNodeIP;

                // ** Getting supernode IP FirstTime
                StringBuilder sb4 = new StringBuilder();
                sb1 = CreateTressInfo();
                sb4.AppendLine("Initializing: Getting supernode IP FirstTime ");
                sb4.AppendLine("SuperNode IP is: " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                sb4.AppendLine(sb1.ToString());
                ClsLogging.WriteToTresslog(sb4);
                // SuperNode IP is  
                //  VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP         
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "OpenBootStrapHttpClient()--:--App.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

		string GetIP4Address()
		{
			string IP4Address = String.Empty;
			try
			{
				foreach (IPAddress IPA in Dns.GetHostAddresses(System.Net.Dns.GetHostName()))
				{
					if (IPA.AddressFamily.ToString() == "InterNetwork")
					{
						IP4Address = IPA.ToString();
						break;
					}
				}
				return IP4Address;
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "GetIP4Address--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return IP4Address;

			}
		}

		void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			try
			{
				LogOut();
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "MainWindow_Closing--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);

			}

		}

		protected override void OnExit(ExitEventArgs e)
		{
			try
			{
				System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName("Yate");
				for (int i = 0; i < p.Length; i++)
				{
					p[i].Kill();
				}
                System.Diagnostics.Process[] pConsole = System.Diagnostics.Process.GetProcessesByName("VMuktiMonitor");
                for (int j = 0; j < pConsole.Length; j++)
                {
                    pConsole[j].Kill();
                }
				LogOut();
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "OnExit()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);

			}
			base.OnExit(e);

		}

		void LogOut()
		{
			try
			{

				VMuktiAPI.VMuktiHelper.CallEvent("LogoutBuddyList", this, new VMuktiEventArgs());
				//bool isSuperNode = false;
				//if (chHttpBootStrapService != null)
				//{
				//    if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == PeerType.BootStrap || VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == PeerType.SuperNode)
				//    {
				//        isSuperNode = true;
				//    }
				//    chHttpBootStrapService.svcHttpBSUnJoin(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, isSuperNode);
				//}
				//if (chHttpSuperNodeService != null)
				//{
				//    chHttpSuperNodeService.svcUnjoin(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
				//}

				// Meet Code For Buddylist Implementation.
				//if (isSuperNode)
				//{
				//    if (VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName != null && VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName != string.Empty)
				//    {
				//        //fncSNDeleteBuddy(uName);
				//        fncSNInsertBuddy(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, "Offline");
				//        fncSNDeleteNode(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
				//        fncUpdateUserBuddyStatus(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, "Offline");
				//    }
				//}
				// End Meet Code.

			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "LogOut()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);

			}
		}

		private void StartUpload()
		{
			try
			{
				if (!System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations"))
				{
					System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Presentations");
				}
				clsPresentationUpload c = new clsPresentationUpload();
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "StartUpload()--:--App.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
		}

		//#region DataBase Creation Function

		//public static string ClientConnectionString = @"Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
		//public static string FilePath = AppDomain.CurrentDomain.BaseDirectory + "AllocateConferenceNumber.sdf";
		//public static bool IsTableExits(string strTableName)
		//{
		//    SqlCeConnection ce = new SqlCeConnection(ClientConnectionString);
		//    try
		//    {
		//        if (!System.IO.File.Exists(FilePath))
		//        {
		//            return false;
		//        }
		//        else
		//        {                    
		//            ce.Open();
		//            string str = "SELECT COUNT(*) FROM Information_Schema.Tables WHERE (TABLE_NAME ='" + strTableName + "')";
		//            SqlCeCommand cmd = new SqlCeCommand(str, ce);
		//            object i = cmd.ExecuteScalar();
		//            ce.Close();
		//            ce.Dispose();
		//            if (int.Parse(i.ToString()) > 0)
		//            {
		//                return true;
		//            }
		//            else
		//            {
		//                return false;
		//            }
		//        }


		//    }
		//    catch (Exception ex)
		//    {
		//        ex.Data.Add("My Key", "IsTableExits()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
		//        ClsException.LogError(ex);
		//        ClsException.WriteToErrorLogFile(ex);
		//        if(ce.State == ConnectionState.Open)
		//        {
		//            ce.Close();					
		//        }
		//        ce.Dispose();
		//        return false;
		//    }
		//}

		//private static bool IsRecordExists(string strBuddyName, string strTableName, string strPrimaryKey)
		//{
		//    SqlCeConnection ce = new SqlCeConnection(ClientConnectionString);
		//    try
		//    {
		//        if (IsTableExits(strTableName))
		//        {
		//            ce.Open();
		//            string str = "SELECT COUNT(*) FROM " + strTableName + " WHERE (" + strPrimaryKey + " ='" + strBuddyName + "')";
		//            SqlCeCommand cmd = new SqlCeCommand(str, ce);

		//            object i = cmd.ExecuteScalar();
		//            ce.Close();
		//            ce.Dispose();
		//            if (int.Parse(i.ToString()) > 0)
		//            {
		//                return true;
		//            }
		//            else
		//            {
		//                return false;
		//            }
		//        }
		//        else
		//        {
		//            return false;
		//        }
		//    }
		//    catch (Exception ex)
		//    {
		//        ex.Data.Add("My Key", "LogOut()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
		//        ClsException.LogError(ex);
		//        ClsException.WriteToErrorLogFile(ex);
		//        if(ce.State == ConnectionState.Open)
		//        {
		//            ce.Close();
		//        }
		//        ce.Dispose();
		//        return false;
		//    }

		//}

		//public static void fncSNInsertBuddy(string strBuddyName, string strBuddyStatus)
		//{
		//    SqlCeConnection ceConn = new SqlCeConnection(ClientConnectionString); 
		//    try
		//    {

		//        if (System.IO.File.Exists(FilePath))
		//        {
		//            if (!IsRecordExists(strBuddyName, "Node_Status", "Buddy_Name"))
		//            {
		//                ceConn.Open();
		//                string str = "insert into Node_Status(Buddy_Name,Buddy_Status) values(@Buddy_Name,@Buddy_Status) ";
		//                SqlCeCommand cmd = new SqlCeCommand(str);
		//                cmd.Connection = ceConn;

		//                cmd.Parameters.AddWithValue("@Buddy_Name", strBuddyName);
		//                cmd.Parameters.AddWithValue("@Buddy_Status", strBuddyStatus);
		//                cmd.ExecuteNonQuery();
		//                ceConn.Close();
		//                ceConn.Dispose();
		//            }
		//            else
		//            {

		//                ceConn.Open();
		//                string str = "Update Node_Status Set Buddy_Status='" + strBuddyStatus + "' Where Buddy_Name='" + strBuddyName + "'";
		//                SqlCeCommand cmd = new SqlCeCommand(str);
		//                cmd.Connection = ceConn;
		//                cmd.ExecuteNonQuery();
		//                ceConn.Close();
		//                ceConn.Dispose();
		//            }
		//        }
		//    }
		//    catch (Exception ex)
		//    {
		//        //Console.WriteLine("Error In Inserting Value from NodeStatus table on SuperNdoeMachine");
		//        ex.Data.Add("My Key", "fncSNInsertBuddy()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
		//        ClsException.LogError(ex);
		//        ClsException.WriteToErrorLogFile(ex);
		//        if(ceConn.State == ConnectionState.Open)
		//        {
		//            ceConn.Close();
		//        }
		//        ceConn.Dispose();
		//    }
		//} 

		//private void fncSNDeleteNode(string uName)
		//{
		//    SqlCeConnection ceConn = new SqlCeConnection(ClientConnectionString);
		//    try
		//    {
		//        if (System.IO.File.Exists(FilePath))
		//        {
		//            if (IsRecordExists(uName, "Node_Info", "Node_Name"))
		//            {                        
		//                ceConn.Open();
		//                string str = "delete from Node_Info where Node_Name = @Node_Name";
		//                SqlCeCommand cmd = new SqlCeCommand(str);
		//                cmd.Connection = ceConn;

		//                cmd.Parameters.AddWithValue("@Node_Name", uName);
		//                cmd.ExecuteNonQuery();
		//                ceConn.Close();
		//                ceConn.Dispose();
		//            }
		//        }
		//    }
		//    catch (Exception ex)
		//    {
		//        //Console.WriteLine("Error In Deleteing Value from NodeInfo table on SuperNdoeMachine.");
		//        ex.Data.Add("My Key", "fncSNDeleteNode()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
		//        ClsException.LogError(ex);
		//        ClsException.WriteToErrorLogFile(ex);
		//        if(ceConn.State == ConnectionState.Open)
		//        {
		//        ceConn.Close();
		//        ceConn.Dispose();
		//        }
		//    }
		//}


		//private void fncUpdateUserBuddyStatus(string BuddName, string status)
		//{
		//    SqlCeConnection ceConn = new SqlCeConnection(ClientConnectionString);
		//    try
		//    {				
		//        ceConn.Open();
		//        //string strCommand = "Select Count(*) From User_BuddyList Where UserName = '" + userName + "' and BuddyName = '" + BuddName + "'";

		//        //SqlCeCommand cmd = new SqlCeCommand("SELECT COUNT(*) FROM User_BuddyList WHERE (UserName = '" + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName + "') AND (BuddyName = '" + BuddName + "')", ceConn);
		//        //object i = cmd.ExecuteScalar();
		//        //if (int.Parse(i.ToString()) > 0)
		//        //{
		//        //    cmd = new SqlCeCommand("Update User_BuddyList Set BuddyStatus='" + status + "' Where (UserName = '" + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName + "') AND (BuddyName = '" + BuddName + "')", ceConn);
		//        //    cmd.ExecuteNonQuery();
		//        //}
		//        SqlCeCommand cmd = new SqlCeCommand("Update User_BuddyList Set BuddyStatus='" + status + "' Where BuddyName = '" + BuddName + "'", ceConn);
		//        cmd.ExecuteNonQuery();
		//        ceConn.Close();
		//        ceConn.Dispose();
		//    }
		//    catch (Exception ex)
		//    {
		//        ex.Data.Add("My Key", "fncUpdateUserBuddyStatus()--:--App.xmal.cs--:--" + ex.Message + " :--:--");
		//        ClsException.LogError(ex);
		//        ClsException.WriteToErrorLogFile(ex);
		//        ceConn.Close();
		//        ceConn.Dispose();
		//    }
		//}
		//#endregion

		#region Detection of Node / SuperNode

		bool FncInLan(string serverIP)
		{
			try
			{
				foreach (IPAddress ipaddress in (System.Net.Dns.GetHostEntry(System.Environment.MachineName)).AddressList)
				{
					if (ipaddress.ToString().Substring(0, 7) == serverIP.Substring(0, 7))
						return true;
				}

				return false;
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "FncInLan()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return false;
			}
		}




		bool FncIsLiveIP()
		{
			try
			{
				int i = 0;
				WebRequest myRequest = WebRequest.Create("http://network-tools.com");
				WebResponse res = myRequest.GetResponse();
				Stream s = res.GetResponseStream();
				StreamReader sr = new StreamReader(s, Encoding.UTF8);
				string html = sr.ReadToEnd();
				Regex regex = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
				string OipString = regex.Match(html).Value;
				ClsException.WriteToLogFile("ip Address is ::" + OipString);
				string hostName = Dns.GetHostName();
				IPHostEntry local = Dns.GetHostEntry(hostName);
				foreach (IPAddress ipaddress in local.AddressList)
				{
					if (OipString == ipaddress.ToString())
					{
						i = 1;
						ClsException.WriteToLogFile("Is LIve IP is ::" + i.ToString());
						ClsException.WriteToLogFile("ip Address is ::" + ipaddress.ToString());
						return true;
					}
				}
				if (i != 1)
				{
					ClsException.WriteToLogFile("Is LIve IP is ::" + i.ToString());
					return false;
				}

				return false;
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "FncIsLiveIP()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return false;
			}
			finally
			{

			}
		}

		bool FncVistaOS()
		{
			try
			{
				System.OperatingSystem osInfo = System.Environment.OSVersion;
				if (osInfo.Version.Major.ToString() == "6")
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "FncVistaOS()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return false;
			}
		}

		bool FncCheckPort(string HostName, object portNoObj)
		{
			try
			{
				int portNo = (int)portNoObj;
				TcpClient TcpScan = new TcpClient();
				TcpScan.Connect(HostName, portNo);
				if (!TcpScan.Connected)
				{
					return false;
				}
				else
					return true;
			}
			catch (Exception ex)
			{

				ex.Data.Add("My Key", "FncCheckPort()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return false;
			}

		}

		bool FncFireWall()
		{
			return false;
			try
			{
				string NatType;
				m_pGet_Click(out  NatType);
				if (NatType == "FullCone" || NatType == "OpenInternet")
				{
					return false;
				}
				else
				{
					return true;
				}
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "FncFireWall()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return false;
			}
		}

		bool FncLocalFirewall()
		{
			try
			{
				VMukti.Presentation.WinXPSP2FireWall fw = new VMukti.Presentation.WinXPSP2FireWall();
				fw.Initialize();
				Boolean b = new Boolean();
				fw.IsWindowsFirewallOn(ref b);
				if (b == false)
					return b; //FireWall Off
				else
					//FireWall ON
					return b;
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "FncLocalFirewall()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return false;
			}
		}

		bool FncVistaLocalFireWall()
		{
			try
			{
				Microsoft.Win32.RegistryKey regKey;
				regKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\PublicProfile");
				string[] s = regKey.GetValueNames();
				string s1 = (string)regKey.GetValue(s[0].ToString()).ToString();
				if (s1 == "0")
				{
					return false;
				}
				else
				{
					return true;
				}
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "FncVistaLocalFireWall()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return true;
			}
		}

		bool FncPort80Free()
		{
			try
			{
				object objHttpBootStrap = null;
				objHttpBootStrap = new BootStrapDelegates();
				BasicHttpServer bhsHttpBootStrap = new BasicHttpServer(ref objHttpBootStrap, "http://" + GetIP4Address() + ":80/HttpBootStrap");
				bhsHttpBootStrap.AddEndPoint<IHTTPBootStrapService>("http://" + GetIP4Address() + ":80/HttpBootStrap");
				bhsHttpBootStrap.OpenServer();
				bhsHttpBootStrap.CloseServer();
				return true;
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "FncPort80busy()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return false;
			}

		}

		bool FncPort4000Free()
		{
			try
			{
				NetPeerServer npsTestServer = new NetPeerServer("net.tcp://" + GetIP4Address() + ":4000/NetP2PTest");
				npsTestServer.AddEndPoint("net.tcp://" + GetIP4Address() + ":4000/NetP2PTest");
				npsTestServer.OpenServer();
				npsTestServer.CloseServer();
				return true;
			}
			catch (Exception ex)
			{
				ex.Data.Add("My Key", "FncPort4000busy()--:--App.xaml.cs--:--" + ex.Message + " :--:--");
				ClsException.LogError(ex);
				ClsException.WriteToErrorLogFile(ex);
				return false;
			}

		}

		public static void m_pGet_Click(out string NatType)
		{
			try
			{
				Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
				socket.Bind(new IPEndPoint(IPAddress.Any, 0));

				STUN_Result result = null;
				result = STUN_Client.Query("stunserver.org", 3478, socket);/*3478*///www.stunserver.org
				NatType = result.NetType.ToString();
			}
			catch (Exception x)
			{
				NatType = null;
			}
		}

		#endregion

		#region IDisposable Members

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		private void Dispose(bool disposing)
		{
			if (!this.disposed)
			{
				if (disposing)
				{
					try
					{
						if (chHttpBootStrapService != null)
						{
							chHttpBootStrapService = null;
						}
						if (objHttpBootStrap != null)
						{
							objHttpBootStrap = null;
						}

						if (App.chNetP2PSuperNodeChannel != null)
						{
							((NetPeerClient)App.objNetP2PSuperNode).CloseClient<INetP2PSuperNodeChannel>();
							App.chNetP2PSuperNodeChannel = null;
						}
						if (App.objNetP2PSuperNode != null)
						{
							App.objNetP2PSuperNode = null;
						}
						//if (chHttpAuthSuperNodeService != null)
						//{
						//    chHttpAuthSuperNodeService = null;
						//}
						//if (objHttpAuthSuperNode != null)
						//{
						//    objHttpAuthSuperNode = null;
						//}
						if (chHttpSuperNodeService != null)
						{
							chHttpSuperNodeService = null;
						}
						if (objHttpSuperNode != null)
						{
							objHttpSuperNode = null;
						}
						if (objNetP2PSuperNode != null)
						{
							objNetP2PSuperNode = null;
						}
						if (chNetP2PSuperNodeChannel != null)
						{
							chNetP2PSuperNodeChannel = null;
						}
						//if (objNetP2PBootStrapActiveCallReport != null)
						//{
						//    objNetP2PBootStrapActiveCallReport = null;
						//}
						//if (chNetP2PBootStrapActiveCallReportChannel != null)
						//{
						//    chNetP2PBootStrapActiveCallReportChannel = null;
						//}
						//if (objNetP2PBootStrapActiveAgentReport != null)
						//{
						//    objNetP2PBootStrapActiveAgentReport = null;
						//}
						//if (chNetP2PBootStrapActiveAgentReportChannel != null)
						//{
						//    chNetP2PBootStrapActiveAgentReportChannel = null;
						//}
						if (DomainSetUp != null)
						{
							DomainSetUp = null;
						}
						if (thBootStrapDomain != null)
						{
							thBootStrapDomain = null;
						}
						if (thSuperNodeDomain != null)
						{
							thSuperNodeDomain = null;
						}
					}
					catch (Exception ex)
					{
						ex.Data.Add("My Key", "VMukti--:--VmuktiModules--:--Audio--:--Audio.Presentation--:--ctlDialer.xaml.cs--:--Dispose()--");
						ClsException.LogError(ex);
						ClsException.WriteToErrorLogFile(ex);
					}
				}
				disposed = true;
			}
			GC.SuppressFinalize(this);
		}

		~App()
		{
			Dispose(false);
		}

		#endregion

        #region logging function

        public static StringBuilder CreateTressInfo()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("User Is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
            sb.AppendLine();
            sb.Append("Peer Type is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
            sb.AppendLine();
            sb.Append("User's SuperNode is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
            sb.AppendLine();
            sb.Append("User's Machine Ip Address : " + VMuktiAPI.GetIPAddress.ClsGetIP4Address.GetIP4Address());
            sb.AppendLine("---------------------------------------------------------------------------------------------");
            return sb;
        }

        #endregion

	}
}
